package AliDiepPR.hWriting;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import AliDiepPR.ANN.Learn;
import AliDiepPR.ANN.Network;
import AliDiepPR.ANN.NeuralNetworkException;
import AliDiepPR.ANN.ReaderWriterNetwork;
import AliDiepPR.ANN.ActivationFunction.SigmoidFunction;
import AliDiepPR.Util.*;
import AliDiepPR.hWriting.R;

public class HWritingActivity extends Activity implements OnClickListener {
	private static final String TAG = "hWritting";

	/*
	 * private String[] charArray = new String[] { "A", "Ă", "Â", "B", "C", "D",
	 * "Đ", "E", "Ê", "G", "H", "I", "K", "L", "M", "N", "O", "Ô", "Ơ", "P",
	 * "Q", "R", "S", "T", "U", "Ư", "V", "X", "Y" };
	 */
	private String[] charArray = new String[] { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9" };
	public static WriteView writeView;
	Button btnSubmit;
	TextView result;
	Network network;
	Learn teach;
	Bitmap image;
	float[] input;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		try {
			network = ReaderWriterNetwork.ReadNetwork(getResources()
					.openRawResource(R.raw.number_1_92));
			teach = new Learn(network, 0.01f, new SigmoidFunction());
		} catch (NeuralNetworkException e) {
			network = null;
			e.printStackTrace();
		} catch (NotFoundException e) {
			network = null;
			e.printStackTrace();
		} catch (IOException e) {
			network = null;
			e.printStackTrace();
		}

		writeView = (WriteView) findViewById(R.id.writeView);
		// writeView.setDrawingCacheEnabled(true);
		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		result = (TextView) findViewById(R.id.tvResult);

		btnSubmit.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSubmit:
			//Intent intent = new Intent(this, Test.class);
			//startActivity(intent);
			Submit();
			break;
		}
	}

	private void Submit() {
		image = writeView.getImage();
		// writeView.setDrawingCacheEnabled(false);
		if (image == null)
			result.setText("No image");
		else {
			
			int temp[][] = AliDiepPR.Util.ImageProcessing.getZone(new Size(16,
					16), image);
			String output = "";
			for (int i = 0; i < temp.length; i++) {
				input = new float[temp[i].length - 2];
				for (int j = 2; j < temp[i].length; j++)
					input[j - 2] = (float) temp[i][j];

				output += teach.getOutput(network, input, charArray);

			}
			result.setText(output);

			// result.setText("A");
			writeView.resetView();
		}
	}
}